package net.crashtoot.picasa.local.presentation;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;

import net.crashtoot.picasa.local.domain.LocalAlbum;
import net.crashtoot.picasa.local.service.LocalExplorerService;

public class ExplorerPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    private final LocalExplorerService explorerService = new LocalExplorerService();
    private JSplitPane splitPane;
    private JPanel albumsPanel;
    private JPanel photosPanel;

    private JPanel toolBar;

    public ExplorerPanel() {

        initComponents();

    }

    private void initComponents() {
        setLayout(new BorderLayout());

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

        albumsPanel = new JPanel(new GridLayout(0, 1));

        photosPanel = new JPanel(new GridLayout(0, 5));

        splitPane.add(albumsPanel, JSplitPane.LEFT);
        splitPane.add(photosPanel, JSplitPane.RIGHT);

        add(splitPane, BorderLayout.CENTER);

        toolBar = new JPanel(new FlowLayout());
        JButton btnOpen = new JButton(new OpenAction());
        toolBar.add(btnOpen);

        add(toolBar, BorderLayout.NORTH);
    }

    private void loadLocalAlbums(final File root) {
        albumsPanel.removeAll();
        List<LocalAlbum> albums = explorerService.listALbums(root.getAbsolutePath());

        if (albums != null) {
            for (LocalAlbum localAlbum : albums) {
                JButton albumBtn = new JButton(new LoadPhotosAction(localAlbum));

                albumsPanel.add(albumBtn);
            }
        }
    }

    public class OpenAction extends AbstractAction {
        private static final long serialVersionUID = 1L;

        private File lastSelection = new File(".");

        public OpenAction() {
            super("Open");
        }

        @Override
        public void actionPerformed(final ActionEvent e) {
            JFileChooser chooser = new JFileChooser();

            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setCurrentDirectory(lastSelection);

            int result = chooser.showOpenDialog(ExplorerPanel.this);
            if (result == JFileChooser.OPEN_DIALOG) {
                lastSelection = chooser.getSelectedFile();

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        loadLocalAlbums(lastSelection);
                    }
                });
            }
        }
    }

    public void loadPhotos(final LocalAlbum album) {
        photosPanel.removeAll();

        for (File photo : album.getImages()) {
            JLabel label = new JLabel(createImageIcon(photo, photo.getName()));
            photosPanel.add(label);
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected ImageIcon createImageIcon(final File file, final String description) {
        try {
            URL imgURL = file.toURI().toURL();

            ImageIcon icon = new ImageIcon(imgURL, description);

            ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(icon.getImage(), 100, 100));

            return thumbnailIcon;
        } catch (Exception e) {
            System.err.println("Couldn't find file: " + file.getAbsolutePath());
            return null;
        }
    }

    /**
     * Resizes an image using a Graphics2D object backed by a BufferedImage.
     * 
     * @param srcImg
     *            - source image to scale
     * @param w
     *            - desired width
     * @param h
     *            - desired height
     * @return - the new resized image
     */
    private Image getScaledImage(final Image srcImg, final int w, final int h) {
        BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();
        return resizedImg;
    }

    public class LoadPhotosAction extends AbstractAction {

        private static final long serialVersionUID = 1L;

        private final LocalAlbum localAlbum;

        public LoadPhotosAction(final LocalAlbum localAlbum) {
            super(localAlbum.getName());
            this.localAlbum = localAlbum;
        }

        @Override
        public void actionPerformed(final ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    loadPhotos(localAlbum);
                }
            });
        }

    }
}